package com.jues.huichain.jsweb;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.design.widget.Snackbar;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.File;

import health.lm.com.data.App;
import health.lm.com.data.HttpCST;
import health.lm.com.network.EasyHttp;
import health.lm.com.network.callback.DownloadProgressCallBack;
import health.lm.com.network.callback.SimpleCallBack;
import health.lm.com.network.exception.ApiException;
import health.lm.com.network.utils.MyApi;

/**
 * Created by Android Studio .
 * Project：hlian com.jues.huichain.jsweb
 * Date：2019/8/28 16:10
 * Introduce：Js交互
 */
public class JsWebModel {
    private static JsWebModel sJsWebModel;

    private JsWebModel() {
    }

    public static JsWebModel getInstance() {
        if (null == sJsWebModel) sJsWebModel = new JsWebModel();
        return sJsWebModel;
    }

    /**
     * 打开文件
     */
    private static void openFile(Context context, File f) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(f).toString());
        String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        //7.0以上需要
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(context, "com.jues.huichain", f);
            intent.setDataAndType(uri, mimetype);
        } else {
            intent.setDataAndType(Uri.fromFile(f), mimetype);
        }
        context.startActivity(intent);
    }

    @SuppressLint("SdCardPath")
    void downLoad(DownFileEntity pEntity, Activity pActivity, View pView) {
        EasyHttp.downLoad(pEntity.getUrl()).savePath("/sdcard/huilian/download")
                .saveName(pEntity.getName() + "." + pEntity.getExt())
                .execute(new DownloadProgressCallBack<String>() {
                    @Override
                    public void update(long bytesRead, long contentLength, boolean done) {
                        long bi = bytesRead / contentLength * 100;
                        //Snackbar.make(pView, bi + "%", 1000).show();
                    }

                    @Override
                    public void onComplete(String path) {
                        Snackbar.make(pView, "下载完成，文件保存在" + path, 5000)
                                .setAction("查看", v -> openFile(pActivity, new File(path))
                                ).show();
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(ApiException e) {
                        Toast.makeText(pActivity, "下载失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 新闻点赞
     *
     * @param id 新闻Id
     */
    void zan(String id, SimpleCallBack<Object> pCallBack) {
        //todo 点赞
        JSONObject jsonObject = new JSONObject();
        String json = "";
        try {
            jsonObject.put(HttpCST.ACCESS_TOKEN, App.model.getAccess_token());
            jsonObject.put("news_id", id);
            json = MyApi.getInstance().generateMessage(HttpCST.MODULE_MEMBER, HttpCST.INTFC_1033, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        EasyHttp.post("/").upJson(json).execute(pCallBack);
    }

    /**
     *  资讯、新闻详情 60秒增加能量
     * @param id
     * @param pCallBack
     */
    void energy(String id, SimpleCallBack<EnergyEntity> pCallBack) {
        JSONObject jsonObject = new JSONObject();
        String json = "";
        try {
            jsonObject.put(HttpCST.ACCESS_TOKEN, App.model.getAccess_token());
            jsonObject.put("news_id", id);
            json = MyApi.getInstance().generateMessage(HttpCST.MODULE_CREDIT, HttpCST.INTFC_1005, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        EasyHttp.post("/").upJson(json).execute(pCallBack);
    }
}
